package org.greyhawk.samonitor.domain;

import javax.persistence.Entity;
import javax.persistence.Table;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.entity.RooEntity;

import javax.validation.constraints.NotNull;
import javax.persistence.ManyToOne;
import javax.persistence.JoinColumn;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.OneToMany;

@Entity
@RooJavaBean
@RooToString
@Table(name = "E_SITE")
@RooEntity(finders = { "findSitesByUrlPath", "findSitesByMainSite" })
public class Site implements Serializable{

	private static final long serialVersionUID = 1L;

	@NotNull
    private String name;

    @NotNull
    private String urlPath;

    @ManyToOne
    @JoinColumn(name="MAIN_SITE_ID")
    private org.greyhawk.samonitor.domain.Site mainSite;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy="mainSite")
    private Set<org.greyhawk.samonitor.domain.Site> channels = new HashSet<org.greyhawk.samonitor.domain.Site>();
    
    
    public List<Site> getChannelList(){
    	List<Site> list = new ArrayList<Site>(this.getChannels());
    	return list;
    }
    
    @SuppressWarnings("unchecked")
	public static List<Site> findMainSites(int startPosition,int maxResult){
    	String qlString = "from Site as site where site.mainSite is null";
		List<Site> sites = Site.entityManager().createQuery(qlString).setFirstResult(startPosition).setMaxResults(maxResult).getResultList();
		return sites;
    }
    
    public static Long findMainSitesCount(){
    	String qlString = "select count(*) from Site as site where site.mainSite is null";
    	return (Long)Site.entityManager().createQuery(qlString).getSingleResult();
    }
    
}
